package com.nc.delivery_project.client.add_user;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.nc.delivery_project.client.ClientFactory;
import com.nc.delivery_project.client.request.UserRequest;
import com.nc.delivery_project.shared.proxy.RoleProxy;
import com.nc.delivery_project.shared.proxy.UserProxy;

import java.util.List;

/**
 * Created by miroshnik on 1/10/2015.
 */
public class AddUserActivity extends AbstractActivity implements AddUserPresenter {
    
    private ClientFactory clientFactory;
    
    private AddUserView view;
    
    private List<RoleProxy> roles;

    public AddUserActivity(Place place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        if (view == null) 
            view = new AddUserView();
        
        view.setPresenter(this);
        
        panel.setWidget(view);
        
        fetchRoles();
    }

    @Override
    public void goTo(Place place) {
        clientFactory.getPlaceController().goTo(place);
    }

    @Override
    public ClientFactory getClientFactory() {
        return clientFactory;
    }

    @Override
    public void registration() {
        UserRequest request = clientFactory.getRequestFactory().createUserRequest();

        UserProxy user = request.create(UserProxy.class);
        user.setEmail(view.emailTxtBox.getText());
        user.setPassword(view.passTxtBox.getText());
        user.setRole(roles.get(view.roleLstBox.getSelectedIndex()));

        request.create(user).fire();
    }

    @Override
    public void fillRoleDropBox(List<RoleProxy> roles) {
        for (RoleProxy role : roles) {
            view.roleLstBox.addItem(role.getTitle(), String.valueOf(role.getId()));
        }
    }

    private void fetchRoles() {
        clientFactory.getRequestFactory().createRoleRequest().read().fire(new Receiver<List<RoleProxy>>() {
            @Override
            public void onSuccess(List<RoleProxy> response) {
                GWT.log("roles fetched");
                roles = response;
                
                fillRoleDropBox(roles);
            }
        });
    }
}
